package guava;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author Daniel
 */
public class CacheLoaderTest {

    /**
     * 数据加载逻辑
     */
    private static final CacheLoader<Long, User> USER_CACHE_LOADER = new CacheLoader<Long, User>() {
        @Override
        public User load(Long id) throws Exception {
            // 模拟数据源、Redis、缓存中加载数据
            User user = new User();
            user.setId(id);
            user.setName(Thread.currentThread().getName()
                    + "-"
                    + LocalDateTime.now().toString());

            System.out.println("loaded user = " + user);
            return user;
        }
    };

    /**
     * 定义缓存策略，提供对外访问缓存
     */
    private static LoadingCache<Long, User> userCacheData = CacheBuilder.newBuilder()
            .expireAfterAccess(2, TimeUnit.SECONDS)
            .expireAfterWrite(2, TimeUnit.SECONDS)
            .refreshAfterWrite(3, TimeUnit.SECONDS)
            .maximumSize(10000L)
            .build(USER_CACHE_LOADER);

    @Data
    private static class User {
        private Long id;
        private String name;
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            User user = null;
            try {
                user = userCacheData.get(1L);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "  user = " + user);
        });
        Thread thread2 = new Thread(() -> {
            User user = null;
            try {
                user = userCacheData.get(1L);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "  user = " + user);
        });

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
